import { goodsList, goodsCount } from '../../../request/api'

interface StateGoods {
    goodslist: Array<object>,
    //pageSize页面显示条数
    pageSize: number,
    //页码
    pageNum: number,
    //总条数
    count: number
}

const state = {
    goodslist: [],
    //pageSize页面显示条数
    pageSize: 3,
    //页码
    pageNum: 1,
    //总条数
    count: 0
}

const getters = {
    getGoods(state: StateGoods) {
        return state.goodslist
    },
    getSize(state: StateGoods) {
        return state.pageSize
    },
    getCount(state: StateGoods) {
        return state.count
    }
}

const mutations = {
    REQ_GOODLIST(state: StateGoods, payload: any) {
        state.goodslist = payload
    },
    REQ_COUNT(state: StateGoods, payload: any) {
        state.count = payload
    },
    //同步修改页码事件
    REQ_PAGE(state: StateGoods, payload: any) {
        state.pageNum = payload
    }
}

const actions = {
    getGoodsListActions(context: any) {
        goodsList({
            size: context.state.pageSize,
            page: context.state.pageNum
        }).then(res => {
            if (res.code == 200) {
                console.log(res, '商品管理行动');
                let list: any = res.list ? res.list : []
                if (context.state.pageNum != 1 && list.length == 0) {
                    //给pageNum -1 并重新调用列表
                    context.dispatch('changePageAction', context.state.pageNum - 1)
                }
                context.commit('REQ_GOODLIST', list)
            }
        })
    },
    //封装一个获取总数的行动
    getCountAction(context:any) {
        goodsCount()
            .then((res:any) => {
                console.log(res, '总数哈哈哈');
                if (res.code == 200) {
                    context.commit('REQ_COUNT', res.list[0].total)
                }
            })
    },
    //获取当前页行动并重新调用列表行动
    changePageAction(context:any, payload:any) {
        //修改页码
        context.commit('REQ_PAGE', payload)
        //重新调用接口 dispatch触发actions  commit提交mutations
        context.dispatch('getGoodsListActions')
    }
}

export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}